package root.user;

import java.util.Comparator;

public class UserDistanceComparator implements Comparator<Location> {

	private Location reference;
	final static double earthRadius = 6371.0; //km
	
	public UserDistanceComparator(Location reference) {
		this.reference = reference;
	}

	/**
	 * Verificacao com if`s dado a incompatibilidade
	 * double - int (distance's return value - compare's return value)
	 * */
	@Override
	public int compare(Location o1, Location o2) {
		double d = distance(o1, reference) - distance(o2, reference);
		int ret = 0;
		if(d < 0) ret = -1;
		if(d > 0) ret = 1;
		return ret;
	}
	
	/**
	 * Retorna a distancia entre as coordenadas
	 * dos parametros dados usando a formula de
	 * Haversine
	 * 
	 * */
	private double distance(Location a, Location b) {
		double dLat = Math.toRadians(b.getLatitude()-a.getLatitude());
		double dLon = Math.toRadians(b.getLongitude()-a.getLongitude());
		double aLat = Math.toRadians(a.getLatitude());
		double bLat = Math.toRadians(b.getLatitude());
		double haversineA = Math.sin(dLat/2) * Math.sin(dLat/2) +
					Math.sin(dLon/2) * Math.sin(dLon/2) *
					Math.cos(aLat) * Math.cos(bLat);
		double haversineB = 2 * Math.atan2(Math.sqrt(haversineA), Math.sqrt(1-haversineA));
		return earthRadius * haversineB;
	}
	
}
